package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entity.File;
import com.entity.StoreHouse;
import com.entity.base.Result;
import com.entity.User;
import com.service.StoreHouseService;
import com.service.oss.OSSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/oss")
@Api(tags = "oss相关接口", description = "提供相关的 Rest API")
public class OSSController {

    @Autowired
    OSSClient ossClient;

    @Autowired
    StoreHouseService storeHouseService;



    @RequestMapping("/upload")//id为资源库id
    @ApiOperation("上传文件")//example:  id="201828034220"  path="local/"  file.name=1.txt   文件路径为:user_space/201828034220/local/1.txt
    private Result upload( @RequestParam("id") String id,@RequestParam("path") String path,
                          @RequestParam("file") MultipartFile file) throws IOException {
        double size = storeHouseService.getById(Long.valueOf(id)).getSize();
        if (size <= 0 || size - (file.getSize()/1024) <= 0) {
            return Result.error("空间不足，请提升您的权限！");
        }
        if (path.length()==2){
            path = id  +"/"+ file.getOriginalFilename();
        }else{
            path = id +"/"+path.split(",")[1]+ file.getOriginalFilename();
        }
        ossClient.putFile(path, file.getBytes());
        return Result.success();

    }

    @ApiOperation("获取文件列表")
    @PostMapping("/getFileList")
    private String getFileList(@RequestBody JSONObject jsonObject) {
        //id:资源库id  path：下级文件夹路径
        String path = jsonObject.get("id").toString() +"/"+ jsonObject.get("path").toString();
        return ossClient.getFileList(path, false);

    }

    @ApiOperation("获取文件夹列表")
    @PostMapping("/getDirList")
    private String getDirList(@RequestBody JSONObject jsonObject) {
        String path = jsonObject.get("id").toString() +"/"+ jsonObject.get("path").toString();
        return ossClient.getFileList(path, true);

    }

    @ApiOperation("删除文件（带id）")
    @PostMapping("/deleteFile")
    private Result deleteFile(@RequestBody JSONObject jsonObject) {
        JSONArray files = jsonObject.getJSONArray("files");
        List<String> list = files.toJavaList(String.class);
        String id = jsonObject.get("id").toString();
        ossClient.deleteFile(list, id);
        return Result.success();

    }

    @ApiOperation("删除文件")
    @PostMapping("/deleteFile_")
    private Result deleteFile_(@RequestBody JSONObject jsonObject){
        String path = jsonObject.get("path").toString();
        ossClient.deleteFile_(path);
        return Result.success();
    }


    @ApiOperation("重命名文件")
    @PostMapping("/reNameFile")
    private Result reNameFile(@RequestBody JSONObject jsonObject) {
        String path = jsonObject.get("path").toString();
        String newPath = jsonObject.get("newPath").toString();

        ossClient.reNameFile( path, newPath);
        return Result.success();

    }

    @ApiOperation("新建文件夹")
    @PostMapping("/mkDir")
    private Result mkDir(@RequestBody JSONObject jsonObject) {
        String path = jsonObject.get("path").toString();
        ossClient.mkDir(path);
        return Result.success();

    }



    @ApiOperation("预览文件")
    @PostMapping("/previewFile")
    private Result previewFile(@RequestBody JSONObject jsonObject) throws IOException {
        String path = jsonObject.get("path").toString();
        return Result.success(ossClient.previewFile(path));

    }

    @RequestMapping("/downloadFile")
    @ResponseBody
        public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        // 浏览器以附件形式下载
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        ossClient.exportOssFile(response.getOutputStream(), objectName);
    }

    @ApiOperation("获取所有文件列表")
    @PostMapping("/getAllFile")
    private Result getAllFile(@RequestBody JSONObject jsonObject) {
        String id = jsonObject.get("id").toString();
        List<OSSObjectSummary> allFile = ossClient.getAllFileList(id);
        ArrayList<File> list = new ArrayList<>();
        for (OSSObjectSummary sum :
                allFile) {
            if (sum.getSize() == 0) continue;
            String key = sum.getKey();
            String name = key.substring(11);
            if (name.length() < 1) continue;
            list.add(new File(name, sum.getSize(), sum.getLastModified()));

        }

        return Result.success(JSON.toJSONString(list));


    }


}
